package com.aaron.sqlsession.impl;

import com.aaron.config.BoundSql;
import com.aaron.config.Configuration;
import com.aaron.config.MappedStatement;
import com.aaron.sqlsession.Executor;
import com.aaron.utils.GenericTokenParser;
import com.aaron.utils.ParameterMapping;
import com.aaron.utils.ParameterMappingTokenHandler;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @Description
 * @Author Aaron
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2021/10/30
 */
public class DefaultExecutor implements Executor {

    private Connection connection;

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object[] param) throws Exception {
        connection = configuration.getDataSource().getConnection();
        String sql = mappedStatement.getSqlText();
        BoundSql boundSql = getBoundSql(sql);
        String sqlText = boundSql.getSqlText();
        PreparedStatement preparedStatement = connection.prepareStatement(sqlText);

        Class<?> paramClass = mappedStatement.getParamType();
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String name = parameterMapping.getContent();
            Field field = paramClass.getDeclaredField(name);
            field.setAccessible(true);
            Object o = field.get(param[0]);
            preparedStatement.setObject(i+1, o);
        }
        ArrayList<Object> results = new ArrayList<>();
        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> resultClass = mappedStatement.getResultType();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object newInstance = resultClass.newInstance();
            for (int i=1; i<=metaData.getColumnCount(); i++) {
                //属性名
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new
                        PropertyDescriptor(columnName, resultClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(newInstance, value);
            }
            results.add(newInstance);
        }
        return (List<E>) results;
    }

    @Override
    public void close() throws SQLException {
        connection.close();
    }

    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{",
                "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings =
                parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parse, parameterMappings);
        return boundSql;
    }
}
